#include "ads7042_port.h"
#include <string.h>
#include "nrf_drv_common.h"
#include "nordic_common.h"
#include "nrf_drv_spi.h"
#include "app_util_platform.h"
#include "app_error.h"
#include "nrfx_spi.h"
#include "nrfx_spim.h"
#include "nrf_gpio.h"
#include "boards.h"
#include "nrf_delay.h"
#include "MyLog.h"
#include "bsp.h"

/* 数据缓冲区和发送控制 */
#define SAMPLE_BUFFER_SIZE 50 // 采样缓冲区大小

/* 波形关键参数配置 */
#define UPPER_THRESH_RATIO 0.8
#define LOWER_THRESH_RATIO 0.5
#define SAMPLE_DELAY_MS 1

static volatile bool spi_xfer_done = false;
static const nrf_drv_spi_t s_spiHandle = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);
static uint8_t spi_tx_buf[256];
static uint8_t spi_rx_buf[256];

static volatile uint16_t g_reference_max = 0;
static volatile uint8_t g_wave_state = 0;
static volatile uint32_t g_sample_count = 0;
static volatile uint32_t g_sample_buffer = 0;
static volatile uint8_t g_init_phase = 1;
static volatile uint16_t g_init_samples[100];
static volatile uint8_t g_init_index = 0;

/**
 @brief SPI中断函数
*/
void spi_event_handler(nrf_drv_spi_evt_t const *p_event, void *p_context)
{

    spi_xfer_done = true;
}

/**
 @brief SPI驱动初始化
 @param 无
 @return 无
*/
void spi_init(void)
{
    ret_code_t errCode;
    nrf_drv_spi_config_t spiConfig = NRF_DRV_SPI_DEFAULT_CONFIG;

    spiConfig.ss_pin = SPI1_SS_PIN;
    spiConfig.miso_pin = SPI1_MISO_PIN;
    spiConfig.mosi_pin = SPI1_MOSI_PIN;
    spiConfig.sck_pin = SPI1_SCLK_PIN;
    spiConfig.mode = NRF_DRV_SPI_MODE_2;
    spiConfig.frequency = SPI_FREQUENCY_FREQUENCY_M1; // 125kHz
    spiConfig.bit_order = NRF_DRV_SPI_BIT_ORDER_MSB_FIRST;
    spiConfig.irq_priority = 2;
    if (nrf_drv_spi_init(&s_spiHandle, &spiConfig, spi_event_handler, NULL) == NRF_SUCCESS)
    {
        MY_LOG_DEBUG("SPI init success./n");
    }
}

void SPI_Disable(void)
{
    nrf_drv_spi_uninit(&s_spiHandle);
}

/**
 * @brief 快速ADC读取（去除串口输出）
    @param 无
    @return ADC读数
 */
uint16_t ADS7042_Readsingle(void)
{

    uint8_t adc_data[2] = {0, 0};
    uint8_t len = 2;

    spi_tx_buf[0] = 0xFF;
    spi_xfer_done = false;

    if (nrf_drv_spi_transfer(&s_spiHandle, spi_tx_buf, len, adc_data, 2) == NRF_SUCCESS)
    {
        while (!spi_xfer_done)
            ;
        uint16_t raw_data = ((uint16_t)(adc_data[0] & 0x3F) << 8) | adc_data[1];
        //		uint16_t raw_data = (uint16_t)adc_data[0] << 8 | adc_data[1];
        float current_voltage = ADS7042_Conv(raw_data, 3.3);

        return (raw_data >> 2) & 0x0FFF;
    }

    return 0;
}

float ADS7042_Conv(uint16_t adc_value, float vref)
{
    return (float)adc_value * vref / 4095.0f;
}

/**
 * @brief 优化的信号处理函数
 */
void Process_Sine_Wave(void)
{
    // 1. 读取当前ADC值
    uint16_t current_adc = ADS7042_Readsingle();
    float current_voltage = ADS7042_Conv(current_adc, 3.3);

    // 2. 初始化阶段：采集前100个点
    if (g_init_phase)
    {
        g_init_samples[g_init_index] = current_adc;
        g_init_index++;

        // 完成100个点采集后计算最大值
        if (g_init_index >= 100)
        {
            uint16_t max_val = 0;
            for (int i = 0; i < 100; i++)
            {
                if (g_init_samples[i] > max_val)
                {
                    max_val = g_init_samples[i];
                }
            }
            g_reference_max = max_val;
            g_init_phase = 0; // 结束初始化阶段

            float ref_voltage = ADS7042_Conv(g_reference_max, 3.3);
            MY_LOG_DEBUG("Init done: %d (%.2fV)\r\n", g_reference_max, ref_voltage);
        }
        return; // 初始化阶段不进行后续处理
    }

    // 3. 动态更新参考值
    if (current_adc > g_reference_max)
    {
        g_reference_max = current_adc;
        float new_ref_voltage = ADS7042_Conv(g_reference_max, 3.3);
        MY_LOG_DEBUG("new refvalue: %d (%.2fV)\r\n", g_reference_max, new_ref_voltage);
    }

    // 4. 计算动态阈值
    float ref_voltage = ADS7042_Conv(g_reference_max, 3.3);
    float upper_threshold = ref_voltage * UPPER_THRESH_RATIO;
    float lower_threshold = ref_voltage * LOWER_THRESH_RATIO;

    // 5. 窗口比较器实现
    uint8_t new_state = g_wave_state; // 默认保持当前状态

    if (current_voltage > upper_threshold)
    {
        new_state = 1;
    }
    else if (current_voltage < lower_threshold)
    {
        new_state = 0;
    }

    // 6. 状态变化检测和输出
    if (new_state != g_wave_state)
    {
        g_wave_state = new_state;
        // MY_LOG_DEBUG("状态切换: %d -> %d, 电压: %.2fV\r\n",
        //              !new_state, new_state, current_voltage);
    }

    // 7. 定期输出调试信息
    g_sample_count++;
    if (g_sample_count % 100 == 0)
    {
        // MY_LOG_DEBUG("采样点: %d, 当前电压: %.2fV, 参考: %.2fV, 状态: %d\r\n",
        //              g_sample_count, current_voltage, ref_voltage, g_wave_state);
    }
}

uint8_t Get_Wave_State(void)
{
    return g_wave_state;
}
